//
//  MYGAcademicConferenceReserveVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/28.
//

import UIKit

class MYGAcademicConferenceReserveVC: MYGBaseController {
    var meeting_id = ""
    var dateModels = [MYGMeetDateModel]()
    var detailModel = MYGMeetDetailDataModel()
    private var contents:[[Any]] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "会议详情"
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        tableView.tableHeaderView = headerView
        let rightItem = UIBarButtonItem(image: UIImage(named: "academicConference_share"), style: .plain, target: self, action: #selector(toShare))
//        navigationItem.rightBarButtonItem = rightItem
        getMeetDate()
    }
    

    lazy var headerView:MYGAcademicReserveHeaderView = {
        let control = MYGAcademicReserveHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 480))
        control.meeting_id = self.meeting_id
        control.getDetailModelCompletion = {[weak self] obj in
            guard let `self` = self else {return}
            self.detailModel = obj
            self.dataFactory()
        }
        return control
    }()
    
    lazy var tableView: UITableView = {
        let control = UITableView.init(frame: .zero, style: .grouped)
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.backgroundColor = .white
//        control.estimatedRowHeight = 170
//        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.ww_foldable = true
        control.register(cellWithClass: MYGAcademicDetailTitleCell.self)
        control.register(cellWithClass: MYGAcademicDetailFooterCell.self)
        control.register(cellWithClass: MYGAcademicDetailFooterView.self)
        control.register(UINib.init(nibName: "MYGAcademicDetailHeaderTitleView", bundle: nil), forHeaderFooterViewReuseIdentifier: "MYGAcademicDetailHeaderTitleView")
        return control
    }()
    
 
    @objc func toShare() {
        MYGCloudDiskPopManager.showComonShare(self.view,meeting_id: meeting_id)
    }
    
}

extension MYGAcademicConferenceReserveVC {
    func getMeetDate() {
        let par = ["meeting_id":meeting_id]
        MYGLoading.show()
        DennyNetwork.request(MYGHomePageAPI.meetingDetailTime(param: par), modelType: [MYGMeetDateModel].self) { obj in
            MYGLoading.hide()
            self.dateModels = obj
            self.headerView.bindDatwModel(dateModels: self.dateModels)
        } failed: { code, message in
            MYGLoading.hide()
            MMYGHUD.showToast(text: message)
        }
    }
    private func dataFactory(){
        self.contents.removeAll()
        self.detailModel.session_info.forEach { obj in
            //区
            var sections:[Any] = []
            var footerCells:[Any] = [] //组转最后显示的时间
            
            obj.speech.forEach { item in
                
                var names:[String] = []
                item.expert.forEach { subObj in
                    
                    let name = "\(subObj.expertCn)(\(subObj.hospital))/\(subObj.expertEn)"
                    names.append(name)
                }
                
                let h:CGFloat = CGFloat(names.count * 20)
                let model = MYGAcademicDetailCellModel(id:item.id,name: item.expertRoleCn, models: names, height: h + 40)//行
                sections.append(model)
                
                if !item.speechCn.isEmpty {
                    names.insert("\(item.speechCn)", at: 0)
                    if(!item.speechEn.isEmpty){
                        names.insert("\(item.speechEn)", at: 1)
                    }
                    //获取 footerCell数据 MYGAcademicDetailFooterCellModel
                    let h = CGFloat(names.count * 20)
                    let lastCellModel = MYGAcademicDetailFooterCellModel(id:item.id,time: item.speechTime, models: names, height:  h + 70)//行
                    footerCells.append(lastCellModel)
                    
                    //点赞 收藏行
                    let footerCellModel = MYGAcademicDetailFooterCollectModel(id: item.id, isShow: false,isLike: item.is_collect)
                    footerCells.append(footerCellModel)
             
                }
            }
            
            if footerCells.count > 0{
                footerCells.forEach { item in
                    sections.append(item)
                }
            }
          
            self.contents.append(sections)
        }
        self.tableView.reloadData()
        tableView.ww_allfoldSection = true
    }
    
    private func submitCollect(model:MYGAcademicDetailFooterCollectModel){
        
        var params:[String:Any] = [:]
        params["collect_status"] = model.isLike == 1 ? "0" : "1"//1收藏 0取消收藏
        params["data_id"] = model.id
        params["type"] = "2"
        
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: params)) { [self] item in
            MYGLoading.hide(self.view)
            model.isLike = model.isLike == 1 ? 0 : 1
            tableView.reloadData()
        } failed: { _, error in
            MYGLoading.hide(self.view)
            MMYGHUD.showToast(text: error)
       }
    }
}

extension MYGAcademicConferenceReserveVC: UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sections = self.contents[indexPath.section]
        let model = sections[indexPath.row]
        if let item = model as? MYGAcademicDetailCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGAcademicDetailTitleCell.self)
            cell.model = item
            return cell
            
        }else if let item = model as? MYGAcademicDetailFooterCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGAcademicDetailFooterCell.self)
            cell.model = item
            return cell
            
        }else if let item = model as? MYGAcademicDetailFooterCollectModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGAcademicDetailFooterView.self)
            cell.model = item
            cell.watchBackButtonBlock = {
                print("回看")
            }
            cell.colloctButtonBlock = {[self] in
                self.submitCollect(model: model as! MYGAcademicDetailFooterCollectModel)
                print("收藏")
            }
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let sections = self.contents[indexPath.section]
        let model = sections[indexPath.row]
        if let item = model as? MYGAcademicDetailCellModel {
            return item.height
        }else if let item = model as? MYGAcademicDetailFooterCellModel {
            return item.height
        }else{
            return 30
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sections = self.contents[section]
        return sections.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.contents.count
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
       let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "MYGAcademicDetailHeaderTitleView") as! MYGAcademicDetailHeaderTitleView
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(gestureTapped(_:)))
        header.addGestureRecognizer(tapGesture)
        header.tag = section
        header.timeLB.text = self.detailModel.session_info[section].sessionTime
        header.contentlB.text = self.detailModel.session_info[section].sessionCn
        header.isExtend = self.tableView.ww_isSectionFolded(section)
        return header
    }
    @objc func gestureTapped(_ ges:UIGestureRecognizer) {
        guard let header = ges.view else {return}
        let section = header.tag
        self.tableView.ww_foldSection(section, fold: !self.tableView.ww_isSectionFolded(section))
    }
}

